package com.wql.crypto;

import java.security.MessageDigest;
import java.util.Random;

import com.wql.crypto.common.HexUtils;

public class SHAUtils {
	private SHAUtils() {
	}

	private static final String ALGORITHM = "SHA-1";// 160

	// private static final String ALGORITHM = "SHA-256";
	// private static final String ALGORITHM = "SHA-384";
	// private static final String ALGORITHM = "SHA-512";

	/**
	 * 标准MD5算法
	 * 
	 * @param data
	 * @return
	 */
	public static String sha(String data) {
		if (null != data)
			try {
				MessageDigest md5 = MessageDigest.getInstance(ALGORITHM);
				byte[] bs = md5.digest(data.getBytes());
				return HexUtils.byte2HexStr(bs);
			} catch (Exception e) {
				e.printStackTrace();
			}
		return null;
	}

	/**
	 * 标准MD5验证方法
	 * 
	 * @param data
	 * @param md5
	 * @return
	 */
	public static boolean verify(String data, String md5) {
		if (null != data)
			return sha(data).equals(md5);
		return false;
	}

	/**
	 * MD5加随机盐，加密后长度为48位，比标准多16位
	 * 
	 * @param data
	 * @return
	 */
	public static String shaWithSalt(String data) {
		Random r = new Random();
		StringBuilder salt = new StringBuilder(20);
		salt.append(r.nextInt(99999999)).append(r.nextInt(99999999));
		int len = salt.length();
		if (len < 20)
			for (int i = 0; i < 20 - len; i++)
				salt.append("0");
		data = sha(data + salt.toString());
		char[] cs = new char[60];
		for (int i = 0; i < 60; i += 3) {
			cs[i] = data.charAt(i / 3 * 2);
			char c = salt.charAt(i / 3);
			cs[i + 1] = c;
			cs[i + 2] = data.charAt(i / 3 * 2 + 1);
		}
		return new String(cs);
	}

	/**
	 * MD5加随机盐验证方法
	 * 
	 * @param data
	 * @param md5
	 * @return
	 */
	public static boolean verifyWithSalt(String data, String md5) {
		if (null != md5 && md5.length() == 60) {
			char[] originMd5 = new char[40];
			char[] salt = new char[20];
			for (int i = 0; i < 60; i += 3) {
				originMd5[i / 3 * 2] = md5.charAt(i);
				originMd5[i / 3 * 2 + 1] = md5.charAt(i + 2);
				salt[i / 3] = md5.charAt(i + 1);
			}
			return verify(data + new String(salt), new String(originMd5));
		}
		return false;
	}

	public static void main(String[] args) {
		String str = "helldsawesd";
		System.out.println(sha(str));
		System.out.println(sha(str).length());
		System.out.println(shaWithSalt(str));
		System.out.println(verify(str, sha(str)));
		System.out.println(verifyWithSalt(str, shaWithSalt(str)));
	}
}
